import { useRequest, useUpdateEffect } from 'ahooks'
import classnames from 'classnames'
import { Card, Timeline } from 'antd'

import { VCenterEmpty } from '@/components/VCenterEmpty'
import { useControllerRef } from '@/hooks/useAbortController'
import { emptyDesc } from '../../utils'
import { withDelayRequest } from '../utils'
import { apiGetOriginalRouteInfo } from './apis'
import { IRouteLine } from './interface'
import styles from './styles.module.less'

const getOriginalRouteInfo = withDelayRequest(apiGetOriginalRouteInfo)

const commonCls = (item: IRouteLine, index: number) => {
  return classnames(
    item.markFlag ? styles.textDelete : '',
    item.routeType === 2 ? styles.textDanger : '',
    item.actionFlag ? styles.textYellow : '',
    index > 1 ? styles.textFilter : '',
  )
}
const dotCls = (item: IRouteLine, index: number) => {
  let cls = index > 1 ? 'rgba(196, 202, 218, 1)' : 'rgba(39, 94, 255, 1)'
  if (item.markFlag) cls = `rgba(216, 26, 26, ${index > 1 ? 0.5 : 1})`
  if (item.actionFlag) cls = `rgba(246, 177, 0, ${index > 1 ? 0.5 : 1})`
  return cls
}

export const RouteLine = ({ waybillNo }: { waybillNo: string }) => {
  const controllerRef = useControllerRef()
  const { loading, data, mutate, run } = useRequest(() => {
    mutate(undefined)
    controllerRef.current.abort()
    controllerRef.current = new AbortController()
    return getOriginalRouteInfo(waybillNo, controllerRef.current.signal)
  })

  useUpdateEffect(() => run(), [waybillNo])

  return (
    <Card style={{ minHeight: 410 }} className={styles.card} loading={loading}>
      {!data?.length ? (
        VCenterEmpty.render({ description: emptyDesc, style: { minHeight: 410 * 0.7 } })
      ) : (
        <Timeline
          mode="left"
          items={data.map((item, index) => {
            return {
              children: (
                <div className={styles.routeContain}>
                  {item.isTitle ? (
                    <div className={classnames(styles.textLabel, commonCls(item, index))}>{item.logisticsStatusEn}</div>
                  ) : (
                    <>
                      <div className={classnames(styles.textNew, commonCls(item, index))}>
                        【{item.routeNodeEn}】{item.titleEn}
                      </div>
                      <div className={classnames(styles.textRoute, commonCls(item, index))}>{item.descEn}</div>
                      <div className={classnames(styles.textTime, commonCls(item, index))}>
                        {item.occurDate} {item.publisher}
                      </div>
                    </>
                  )}
                </div>
              ),
              color: dotCls(item, index),
            }
          })}
        />
      )}
    </Card>
  )
}
